﻿using NaturalNote.Core.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NaturalNote.Mysql
{
    internal class MysqlBuilder<T> where T : class,new()
    {
        private MysqlBuilder() { this.init(); }

        public static MysqlBuilder<T> Instance { get { return Nested.instance; } }

        private class Nested
        {
            //Explicit static constructor to tell C# compiler
            //not to mark type as beforefieldinit
            static Nested()
            {

            }

            internal static readonly MysqlBuilder<T> instance = new MysqlBuilder<T>();
        }

        
        private void init()
        {
            var tableInfo = XTable<T>.Instance.TableInfo;
            var columns = new List<string>();
            var propNames = new List<string>();
            var updateValues = new List<string>();
            foreach (var column in tableInfo.Columns)
            {
                columns.Add($"`{column.Name}`");
                propNames.Add($"@{column.PropName}");
                if (!column.IsPrimary)
                {
                    updateValues.Add($"`{column.Name}`=VALUES(`{column.Name}`)");
                }                
            }
            this.InsertOnUpdateSql = @$"INSERT INTO `{tableInfo.Name}` (
{string.Join(",", columns)} ) 
VALUES ( {string.Join(",", propNames)} )
ON DUPLICATE KEY UPDATE {string.Join(",", updateValues)};";
        }
        public string InsertOnUpdateSql { get; private set; }
    }
}
